package net.wzw.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.wzw.config.OSSConfig;
import net.wzw.service.FileService;
import net.wzw.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @className: FileServiceImpl
 * @author: wzw
 * @date: 2024-08-17 9:23
 * @Version: 1.0
 * @description: 文件上传服务
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    /**
     * 注入 OSS 配置文件
     */
    @Autowired
    private OSSConfig ossConfig;

    /**
     * 上传用户头像
     * @param file
     * @return
     */
    @Override
    public String uploadUserAvatar(MultipartFile file) {
        /**
         * 1、获取 OSS 相关配置
         */
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketname = ossConfig.getBucketname();

        /**
         * 创建 OSS 对象
         */
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        /**
         * 获取原始文件名
         */
        String OriginalFilename = file.getOriginalFilename();

        /**
         * 获取日期格式，上传时目录名使用
         */
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        /**
         * OSS 上传存储路径：user/2024/08/17/xxxxxxx.jpg/png
         */
        String floder = dateTimeFormatter.format(localDateTime);
        // 获取扩展名
        String extension = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        // 新文件名，通过 uuid 生成文件名，
        String fileName = "user/" + floder + "/" + CommonUtil.generateUUID() + extension;

        try {
            // 写入 OSS
            PutObjectResult putObjectResult = ossClient.putObject(bucketname, fileName, file.getInputStream());
            // 返回图片路径
            if (putObjectResult != null) {
                String imgUrl = "https://" + bucketname + "." + endPoint + "/" + fileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.error("用户微服务-上传模块-文件上传失败：{}", e);
            throw new RuntimeException(e);
        } finally {
            // oss 关闭客户端服务，不然会造成 OOM
            ossClient.shutdown();
        }
        return null;
    }
}
